package com.zxq.web.controller.platform;

import com.zxq.web.dto.PlatformCmdComposeDTO;
import com.zxq.web.enums.ESponsor;
import com.zxq.web.iot.domain.IotCmd;
import com.zxq.web.iot.domain.IotCmdDecode;
import com.zxq.web.iot.domain.IotCmdEncoder;
import com.zxq.web.iot.service.impl.IotCmdDecodeServiceImpl;
import com.zxq.web.iot.service.impl.IotCmdEncoderServiceImpl;
import com.zxq.web.iot.service.impl.IotCmdServiceImpl;
import com.zxq.web.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController("cmdCompose")
@Slf4j
public class IotComposeCmdController {


    /**
     * cmd 执行服务
     */
    @Autowired
    IotCmdServiceImpl iotCmdDoService;

    /**
     * cmd 编码服务
     */
    @Autowired
    IotCmdEncoderServiceImpl iotCmdEncoderDoService;

    /**
     * cmd解码服务
     */
    @Autowired
    IotCmdDecodeServiceImpl iotCmdDecodeDoService;


    @PostMapping("generator")
    public ResultVO<Boolean> composeCmd(@RequestBody PlatformCmdComposeDTO platformCmdDTO){
         Long cmdId =  platformCmdDTO.getCmdId();
         IotCmd iotCmdDo = iotCmdDoService.selectIotCmdById(cmdId);
         Integer sponsor =  iotCmdDo.getSponsor().intValue();
         ESponsor eSponsor =  ESponsor.getType(sponsor);
         String[] fields =   platformCmdDTO.getFields().split(",");
         for (String field : fields) {
             Long fieldId = Long.parseLong(field);
             switch (eSponsor) {
                 case device:
                     IotCmdDecode iotCmdDecodeDo = new IotCmdDecode();
                     iotCmdDecodeDo.setCmdId(cmdId);
                     iotCmdDecodeDo.setFieldId(fieldId);
                     iotCmdDecodeDo.setRemark("generator");
                     iotCmdDecodeDoService.insertIotCmdDecode(iotCmdDecodeDo);
                     break;
                 case platform:
                     IotCmdEncoder iotCmdEncoderDo = new IotCmdEncoder();
                     iotCmdEncoderDo.setCmdId(cmdId);
                     iotCmdEncoderDo.setFieldId(fieldId);
                     iotCmdEncoderDo.setRemark("generator");
                     iotCmdEncoderDoService.insertIotCmdEncoder(iotCmdEncoderDo);
                     break;
             }
         }
         ResultVO<Boolean> resultVO = new ResultVO<>();
         resultVO.setSuccess(true);
         resultVO.setCode(200);
         resultVO.setMessage("字段装配完成");
         resultVO.setData(true);
         return resultVO;
    }



}
